package com.buaa.aimall.modelModule.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buaa.aimall.modelModule.DTO.FilterModelDTO;
import com.buaa.aimall.modelModule.DTO.GetModelListDTO;
import com.buaa.aimall.modelModule.Entity.ModelEntity;
import com.buaa.aimall.modelModule.Entity.ModelKeyEntity;
import com.buaa.aimall.userModule.Entity.UserEntity;
import com.buaa.aimall.Utils.Exception.BusinessException;
import com.buaa.aimall.modelModule.Mapper.ModelMapper;
import com.buaa.aimall.Utils.MinioUtils;
import com.buaa.aimall.Utils.PageReturnResult;

import com.buaa.aimall.userModule.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

import com.buaa.aimall.modelModule.Enum.ModelSortTypeEnum;

@Service
public class ModelServiceImpl extends ServiceImpl<ModelMapper, ModelEntity> implements ModelService {
    @Autowired
    private ModelKeyService modelKeyService;

    @Autowired
    private UserService userService;

    @Autowired
    private MinioUtils minioUtils;

    @Override
    public boolean createModel(ModelEntity modelEntity, MultipartFile docFile) {
        if (docFile != null && !docFile.isEmpty()) {
            try {
                String randomString = UUID.randomUUID().toString();
                String fileName = "helper_document/" + randomString + "_" + docFile.getOriginalFilename();
                minioUtils.upload(docFile, fileName);
                modelEntity.setDocURL(fileName);
            } catch (Exception e) {
                throw new BusinessException("文件上传失败: " + e.getMessage());
            }
        }
        if (modelEntity.getModelKey() == null || modelEntity.getModelKey().isEmpty()) {
            ModelKeyEntity modelKeyEntity = new ModelKeyEntity();
            modelKeyService.save(modelKeyEntity);
            modelEntity.setModelKey(modelKeyEntity.getId());
        }
        modelEntity.setIsEnabled(true);
        return this.save(modelEntity);
    }

    @Override
    public List<ModelEntity> getModelList(GetModelListDTO getModelListDTO) {
        IPage<ModelEntity> page = new Page<>(getModelListDTO.getPage(), getModelListDTO.getPageSize());

        UserEntity user = userService.getCurrentUser();
        LambdaQueryWrapper<ModelEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ModelEntity::getCreator, user.getId());

        if (StringUtils.isNotBlank(getModelListDTO.getNameEN())) {
            queryWrapper.like(ModelEntity::getNameEN, getModelListDTO.getNameEN());
        }

        return this.page(page, queryWrapper).getRecords();
    }

    @Override
    public PageReturnResult<ModelEntity> filterModel(FilterModelDTO filterModelDTO) {
        PageReturnResult<ModelEntity> result = new PageReturnResult<>();
        LambdaQueryWrapper<ModelEntity> queryWrapper = new LambdaQueryWrapper<>();
        Integer pageSize = filterModelDTO.getPageSize();
        Integer currentPage = filterModelDTO.getCurrentPage();

        if (filterModelDTO.getId() != null) queryWrapper.eq(ModelEntity::getId, filterModelDTO.getId());
        if (filterModelDTO.getModel_name_en() != null)
            queryWrapper.like(ModelEntity::getNameEN, filterModelDTO.getModel_name_en());
        if (filterModelDTO.getModel_name_zh() != null)
            queryWrapper.like(ModelEntity::getNameZH, filterModelDTO.getModel_name_zh());
        if (filterModelDTO.getModel_type() != null)
            queryWrapper.like(ModelEntity::getType, filterModelDTO.getModel_type());  // 模糊搜索 model_type
        if (filterModelDTO.getFk_creator() != null)
            queryWrapper.like(ModelEntity::getCreator, filterModelDTO.getFk_creator());  // 模糊搜索 creator
        if (filterModelDTO.getImage_url() != null)
            queryWrapper.like(ModelEntity::getImageURL, filterModelDTO.getImage_url());  // 模糊搜索 image_url
        if (filterModelDTO.getCreate_time_start() != null)
            queryWrapper.ge(ModelEntity::getCreateTime, filterModelDTO.getCreate_time_start());
        if (filterModelDTO.getCreate_time_end() != null)
            queryWrapper.le(ModelEntity::getCreateTime, filterModelDTO.getCreate_time_end());
        if (filterModelDTO.getUpdate_time_start() != null)
            queryWrapper.ge(ModelEntity::getUpdateTime, filterModelDTO.getUpdate_time_start());
        if (filterModelDTO.getUpdate_time_end() != null)
            queryWrapper.le(ModelEntity::getUpdateTime, filterModelDTO.getUpdate_time_end());
        if (filterModelDTO.getMemory_size_min() != null)
            queryWrapper.ge(ModelEntity::getMemorySize, filterModelDTO.getMemory_size_min());
        if (filterModelDTO.getMemory_size_max() != null)
            queryWrapper.le(ModelEntity::getMemorySize, filterModelDTO.getMemory_size_max());
        if (filterModelDTO.getModel_status() != null)
            queryWrapper.like(ModelEntity::getStatus, filterModelDTO.getModel_status());  // 模糊搜索 model_status
        if (filterModelDTO.getModel_is_enabled() != null)
            queryWrapper.eq(ModelEntity::getIsEnabled, filterModelDTO.getModel_is_enabled());
        if (filterModelDTO.getModel_description() != null)
            queryWrapper.like(ModelEntity::getDescription, filterModelDTO.getModel_description());  // 模糊搜索 description
        if (filterModelDTO.getModel_rating() != null)
            queryWrapper.eq(ModelEntity::getRating, filterModelDTO.getModel_rating());
        if (filterModelDTO.getSort() != null) {
            addSortConditions(queryWrapper, filterModelDTO.getSort().getCode());
        } else {
            addSortConditions(queryWrapper, ModelSortTypeEnum.DEFAULT.getCode());
        }
        long totalCount = this.count(queryWrapper);
        result.setTotalCount(totalCount);
        // 分页处理
        if (pageSize != null && currentPage != null) {
            IPage<ModelEntity> page = new Page<>(currentPage, pageSize);
            IPage<ModelEntity> modelPage = page(page, queryWrapper);
            result.setRecords(modelPage.getRecords());
        } else {
            result.setRecords(list(queryWrapper));
        }
        return result;
    }

    @Override
    public boolean disableModel(String modelID) {
        QueryWrapper<ModelEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", modelID);
        ModelEntity modelEntity = getOne(queryWrapper);
        if (modelEntity == null)
            throw new BusinessException("错误moduleID");
        if (!modelEntity.getIsEnabled()) {
            throw new BusinessException("模型已下架");
        }
        UpdateWrapper<ModelEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", modelID);
        updateWrapper.set("model_is_enabled", 0);
        return this.update(updateWrapper);
    }

    @Override
    public boolean enableModel(String modelID) {
        QueryWrapper<ModelEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", modelID);
        ModelEntity modelEntity = getOne(queryWrapper);
        if (modelEntity == null)
            throw new BusinessException("错误moduleID");
        if (modelEntity.getIsEnabled() != null && modelEntity.getIsEnabled()) {
            throw new BusinessException("模型已上架");
        }
        UpdateWrapper<ModelEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", modelID);
        updateWrapper.set("model_is_enabled", 1);
        return this.update(updateWrapper);
    }

    @Override
    public Boolean updateModelDoc(String modelID, MultipartFile docFile) {
        ModelEntity modelEntity = this.getById(modelID);
        if (modelEntity == null) {
            throw new BusinessException("未找到指定的模型资源");
        }

        if (docFile != null && !docFile.isEmpty()) {
            try {
                String randomString = UUID.randomUUID().toString();
                String newFileName = "helper_document/" + randomString + "_" + docFile.getOriginalFilename();
                String oldDocURL = modelEntity.getDocURL();

                if (oldDocURL != null && !oldDocURL.isEmpty()) {
                    // 更新现有文档
                    minioUtils.updateFile(oldDocURL, docFile, newFileName);
                    modelEntity.setDocURL(newFileName);
                } else {
                    // 创建新文档
                    minioUtils.upload(docFile, newFileName);
                    modelEntity.setDocURL(newFileName);
                }
                return this.updateById(modelEntity);
            } catch (Exception e) {
                throw new BusinessException("模型文档更新失败: " + e.getMessage());
            }
        }
        return false;
    }

    @Override
    public PageReturnResult<ModelEntity> getHomepageContent(String orderType, Integer currentPage, Integer pageSize, String name) {
        PageReturnResult<ModelEntity> result = new PageReturnResult<>();
        LambdaQueryWrapper<ModelEntity> queryWrapper = new LambdaQueryWrapper<>();

        addSortConditions(queryWrapper, orderType);
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(ModelEntity::getNameEN, name);
        }

        // 获取总记录数
        long totalCount = this.count(queryWrapper);
        result.setTotalCount(totalCount);

        // 分页处理
        if (currentPage != null && pageSize != null) {
            IPage<ModelEntity> page = new Page<>(currentPage, pageSize);
            IPage<ModelEntity> modelPage = page(page, queryWrapper);
            result.setRecords(modelPage.getRecords());
        } else {
            // 如果未指定分页参数，则返回所有符合条件的记录
            List<ModelEntity> modelList = this.list(queryWrapper);
            result.setRecords(modelList);
        }

        return result;
    }

    /**
     * 添加排序条件
     *
     * @param queryWrapper 查询构造器
     * @param sortType     排序类型
     */
    private void addSortConditions(LambdaQueryWrapper<ModelEntity> queryWrapper, String sortType) {
        ModelSortTypeEnum.fromCode(sortType)
                .getSortFunction()
                .accept(queryWrapper);
    }
}
